package xyz.kongbai121.demo.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.kongbai121.demo.domain.Chat;
import xyz.kongbai121.demo.domain.ChatList;
import xyz.kongbai121.demo.mapper.ChatListMapper;
import xyz.kongbai121.demo.mapper.ChatMapper;
import xyz.kongbai121.demo.mapper.UserMapper;
import xyz.kongbai121.demo.service.IChatService;
import xyz.kongbai121.demo.util.UserPowerException;

import java.util.*;

@Service
@Transactional
public class ChatServiceImpl implements IChatService {

    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private ChatListMapper chatListMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public String save(String token, String content, Long toUserId) {
        String openid = redisTemplate.opsForValue().get(token);
        Long userId = userMapper.getUser(openid).getId();
        Chat chat = new Chat(userId, content, toUserId);
        if (userId == null) throw new UserPowerException("请先登录");
        ChatList chatLists = chatListMapper.get(userId, toUserId);
        //TODO  维护聊天列表信息
        if (chatLists == null){
            ChatList chatList = new ChatList(userId, content, toUserId, 1);
            chatListMapper.insert(chatList);
        }else {
            chatLists.setUnreadNum(chatLists.getUnreadNum()+1);
            chatLists.setContent(content);
            chatLists.setOfTime(new Date());
            chatListMapper.updateById(chatLists);
        }
        //TODO  保存私信
        chatMapper.insert(chat);
        return "成功";
    }

    @Override
    public List<ChatList> list(String token) {
        if (token == null || !redisTemplate.hasKey(token)) throw new UserPowerException("请先登录");
        String openid = redisTemplate.opsForValue().get(token);
        Long userId = userMapper.getUser(openid).getId();
        List<ChatList> list = chatListMapper.getList(userId);
        for (ChatList chatList : list) {
            if (chatList.getUserId().equals(userId)) chatList.setUnreadNum(0);
        }
        return list;
    }

    @Override
    public List<Chat> get(Long fromUserId, String token) {
        if (token == null || !redisTemplate.hasKey(token)) throw new UserPowerException("请先登录");
        String openid = redisTemplate.opsForValue().get(token);
        Long toUserId = userMapper.getUser(openid).getId();
        ChatList chatLists = chatListMapper.get(fromUserId, toUserId);
        if (chatLists != null && chatLists.getToUserId().equals(toUserId)){
            chatLists.setUnreadNum(0);
            chatListMapper.updateById(chatLists);
        }
        return chatMapper.get(fromUserId, toUserId);
    }
}
